﻿using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
	public float velocity = 50;
	public float damage = 30;
	public GameObject impact;
	float destroyTime = 5f;

	void Start() {
		GetComponent<Rigidbody> ().AddForce (-transform.up * velocity);
		GetComponent<TrailRenderer>().time = 80/velocity;
	}
	void Update() {
		destroyTime -= Time.deltaTime;
		if (destroyTime < 0)
			Destroy (gameObject);
	}
	void OnTriggerEnter(Collider other) {
		if (other.gameObject.tag != "Player" && !other.isTrigger) {
			GameObject tempImpact = (GameObject)GameObject.Instantiate(impact);
			RaycastHit hit; 
			if(other.tag == "Enemy") {
				other.GetComponent<Enemy>().health -= damage;
			}
			if(Physics.Raycast(transform.position - GetComponent<Rigidbody>().velocity/ 10, GetComponent<Rigidbody>().velocity, out hit)){
				if(hit.collider != null){
					tempImpact.transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
					tempImpact.transform.position = new Vector3(hit.point.x, 0, hit.point.z);
				}
				Destroy(tempImpact, 1.5f);
				Destroy (gameObject);
			}
		}
	}

}
